<?php


namespace App\Http\Controllers\Management;

use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Events\AsynchronousIOFile;
use App\Models\Branch;
use App\Models\ExcelFile;
use App\Http\Controllers\BranchUtils;
use App\Models\Tag;
use Illuminate\Http\Request;
use App\Models\Worker;

class OutPutDataController extends Controller
{
    // 订单导出
    public function getOrderList(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
//        $operation_id = 17;
        $worker_role = Worker::where('id', $operation_id)->with('roles.powers')->with('branchesManage')->first();
        if ($worker_role['branchesManage'] != []) {
            $worker_manage_branch_id = $worker_role['branchesManage'][0]['id'];
            $branch_dic = BranchUtils::getAllBranchs();
            $branch_list = BranchUtils::getChildBranchs($worker_manage_branch_id, $branch_dic, [$worker_manage_branch_id]);
        } else {
            return LMReturn::Error('您没有管理部门');
        }
        $is_roles = 0;
        if (isset($worker_role['roles'])) {
            foreach ($worker_role['roles'] as $roles) {
                if ($roles['powers']) {
                    foreach ($roles['powers'] as $power) {
                        if ($power['id'] == 185) {
                            $is_roles = 1;
                            break;
                        }
                    }
                }
                if ($is_roles == 1) {
                    break;
                }
            }
        }
        if ($is_roles == 0) {
            return LMReturn::selectErr('您没有权限进行数据导出');
        }
        $all = $request->all();
        $branch_id = $all['branch_id'] ?? $worker_manage_branch_id;
        if (in_array($branch_id, $branch_list)) {
            $branch_id_list = BranchUtils::getChildBranchs($branch_id, $branch_dic, [$branch_id]);
        } else {
            return LMReturn::Error('您没有导出该部门的权限');
        }
        $start_time = $all['start_time'] ?? 0;
        $end_time = $all['end_time'] ?? 0;
        $time_chose = $all['time_chose'] ?? 1;
        $order_status = $all['order_status'] ?? [2, 4, 5, 6];
        if ($order_status == [] || $order_status == null || $order_status[0] == null) {
            $order_status = [2, 4, 5, 6];
        }
        $order_status_num = implode('-', $order_status);
        $user_id = $all['user_id'] ?? '';
        $worker_id = $all['worker_id'] ?? '';
        $product_id = $all['product_id'] ?? '';
        $excel_record = new ExcelFile();
        $excel_record->operation_id = $operation_id;
        if ($start_time != 0 && $end_time != 0) {
            $excel_record->start_time = $start_time;
            $excel_record->end_time = $end_time;
        }
        $excel_record->is_success = 3;
        $excel_record->order_status = $order_status_num;
        $excel_record->branch_id = $branch_id;
        $excel_record->time_chose = $time_chose;
        $excel_record->file_type = 1;
        try {
            if ($user_id) {
                $excel_record->user_id = $user_id;
            }
            if ($worker_id) {
                $excel_record->worker_id = $worker_id;
            }
            if ($product_id) {
                $excel_record->product_id = $product_id;
            }
        } catch (\Throwable $th) {
            return LMReturn::insertErr('参数不对', '402');
        }
        $excel_record->save();
        AsynchronousIOFile::dispatch(1, $product_id, $user_id, $worker_id, $start_time, $end_time, $time_chose, $branch_id_list, $order_status, $excel_record->id);
        return response()->json([
            'code'=>200,
            'msg'=>'成功',
            'data'=>[]
        ]);
    }

    // 打款记录导出
    public function getRecordList(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
//        $operation_id = 17;
        $worker_role = Worker::where('id', $operation_id)->with('roles.powers')->with('branchesManage')->first();
        if ($worker_role['branchesManage'] != []) {
            $worker_manage_branch_id = $worker_role['branchesManage'][0]['id'];
            $branch_dic = BranchUtils::getAllBranchs();
            $branch_list = BranchUtils::getChildBranchs($worker_manage_branch_id, $branch_dic, [$worker_manage_branch_id]);
        } else {
            return LMReturn::Error('您没有管理部门');
        }
        $is_roles = 0;
        if (isset($worker_role['roles'])) {
            foreach ($worker_role['roles'] as $roles) {
                if ($roles['powers']) {
                    foreach ($roles['powers'] as $power) {
                        if ($power['id'] == 185) {
                            $is_roles = 1;
                            break;
                        }
                    }
                }
                if ($is_roles == 1) {
                    break;
                }
            }
        }
        if ($is_roles == 0) {
            return LMReturn::selectErr('您没有权限进行数据导出');
        }
        $all = $request->all();
        $branch_id = $all['branch_id'] ?? $worker_manage_branch_id;
        if (in_array($branch_id, $branch_list)) {
            $branch_id_list = BranchUtils::getChildBranchs($branch_id, $branch_dic, [$branch_id]);
        } else {
            return LMReturn::Error('您没有导出该部门的权限');
        }
        $start_time = $all['start_time'] ?? 0;
        $end_time = $all['end_time'] ?? 0;
        $status = $all['status'] ?? [1, 2, 3, 4, 5];       // 1.待打款，2.打款中，3.已打款
        if ($status == [] || $status == '' || $status[0] == null) {
            $status = [1, 2, 3, 4, 5];
        }
        $time_chose = $all['time_chose'] ?? 1;       // 1.根据打款时间，2根据订单的生效时间
        $user_id = $all['user_id'] ?? '';
        $worker_id = $all['worker_id'] ?? '';
        $contract_no = $all['contract_no'] ?? '';
        $excel_record = new ExcelFile();
        $excel_record->operation_id = $operation_id;
        $order_status_num = implode('-', $status);
        $excel_record->order_status = $order_status_num;
        if ($start_time != 0 && $end_time != 0) {
            $excel_record->start_time = $start_time;
            $excel_record->end_time = $end_time;
        }
        $excel_record->is_success = 3;
        $excel_record->branch_id = $branch_id;
        $excel_record->time_chose = $time_chose;
        $excel_record->file_type = 2;
        try {
            if ($user_id) {
                $excel_record->user_id = $user_id;
            }
            if ($worker_id) {
                $excel_record->worker_id = $worker_id;
            }
        } catch (\Throwable $th) {
            return LMReturn::insertErr('参数不对', '402');
        }
        $excel_record->save();
        AsynchronousIOFile::dispatch(2, $contract_no, $user_id, $worker_id, $start_time, $end_time, $time_chose, $branch_id_list, $status, $excel_record->id);
        return response()->json([
            'code'=>200,
            'msg'=>'成功',
            'data'=>[]
        ]);
    }

    // 客户信息导出
    public function getUserList(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
        $worker_role = Worker::where('id', $operation_id)->with('roles.powers')->with('branchesManage')->first();
        if ($worker_role['branchesManage'] != []) {
            $worker_manage_branch_id = $worker_role['branchesManage'][0]['id'];
            $branch_dic = BranchUtils::getAllBranchs();
            $branch_list = BranchUtils::getChildBranchs($worker_manage_branch_id, $branch_dic, [$worker_manage_branch_id]);
        } else {
            return LMReturn::Error('您没有管理部门');
        }
        $all = $request->all();
        $branch_id = $all['branch_id'] ?? $worker_manage_branch_id;
        if (in_array($branch_id, $branch_list)) {
            $branch_id_list = BranchUtils::getChildBranchs($branch_id, $branch_dic, [$branch_id]);
        } else {
            return LMReturn::Error('您没有导出该部门的权限');
        }
        if (isset($all['tag_list'])) {
            $tag_list = $all['tag_list'];
        } else {
            $tag_list = [];
        }
        try {
            $excel_record = new ExcelFile();
            $excel_record->file_type = 3;
            $excel_record->operation_id = $operation_id;
            if (count($tag_list) > 0) {
                $order_status_num = implode('-', $tag_list);
                $excel_record->order_status = $order_status_num;
            }
            $excel_record->branch_id = $branch_id;
            $worker_id = $all['worker_id'] ?? null;
            if ($worker_id) {
                $excel_record->worker_id = $worker_id;
            }
            $excel_record->save();
        } catch (\Throwable $th) {
            return LMReturn::Error('参数不对');
        }
        AsynchronousIOFile::dispatch(3, null, null, $worker_id, null, null, null, $branch_id_list, $tag_list, $excel_record->id);
        return response()->json([
            'code'=>200,
            'msg'=>'成功',
            'data'=>[]
        ]);
    }

    // 导出记录展示
    public function disPlayRecord(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
        $worker_role = Worker::where('id', $operation_id)->with('roles.powers')->first();
        $is_roles = 0;
        if (isset($worker_role['roles'])) {

            foreach ($worker_role['roles'] as $roles) {
                if ($roles['powers']) {
                    foreach ($roles['powers'] as $power) {
                        if ($power['id'] == 186) {
                            $is_roles = 1;
                            break;
                        }
                    }
                }
                if ($is_roles == 1) {
                    break;
                }
            }
        }
        if ($is_roles == 0) {
            return LMReturn::Error('无权查看');
        }
        $worker_role = Worker::where('id', $operation_id)->with('roles.powers')->with('branchesManage')->first();
        if ($worker_role['branchesManage'] != []) {
            $worker_manage_branch_id = $worker_role['branchesManage'][0]['id'];
            $branch_dic = BranchUtils::getAllBranchs();
            $branch_list = BranchUtils::getChildBranchs($worker_manage_branch_id, $branch_dic, [$worker_manage_branch_id]);
        } else {
            return LMReturn::Error('您没有管理部门');
        }
        $all = $request->all();
        $page = $all['page'] ?? 1;
        $size = $all['size'] ?? 15;
        $search_type = $all['search_type'] ?? 3;       // 查询方式：1.只看订单导出记录， 2.只看打款导出记录， 3.全看（默认）
        $is_success = $all['is_success'] ?? 3;          // 查看导出成功和失败的： 1.只看成功的， 2.只看失败的， 3.全看（默认）
        $where = [];
        if ($search_type == 1 || $search_type == 2) {
            $where[] = ['file_type', $search_type];
        }
        if ($is_success == 1 || $is_success == 2) {
            $where[] = ['is_success', $is_success];
        }
        $excel_records = ExcelFile::where($where)->whereIn('branch_id', $branch_list)->with('branch')->with('worker')->with('operation.branches')->with('product')->with('user')->orderBy('id', 'desc')->get();
        $record_list = [];
        foreach ($excel_records as $excel_record) {
            $record_dic = [];
            $filter = [];
            $record_dic['operation_id'] = $excel_record['operation_id'];
            $record_dic['operation_name'] = $excel_record['operation']['name'];
            $record_dic['user_status'] = $excel_record['operation']['user_status'] == 1 ? '在职' : '离职';
            if ($excel_record['operation']['branches']) {
                $record_dic['operation_branch'] = $excel_record['operation']['branches'][0]['name'];
            }
            if ($excel_record['file_type'] == 1) {
                if ($excel_record['order_status'] == "2-4-5-6") {
                    $filter['order_status'] = '查看全部';
                } else {
                    $order_status = $excel_record['order_status'];
                    $order_status = str_replace('2', '审核中', $order_status);
                    $order_status = str_replace('4', '已生效', $order_status);
                    $order_status = str_replace('5', '拒绝', $order_status);
                    $order_status = str_replace('6', '已结束', $order_status);
                    $filter['order_status'] = $order_status;
                }
            } elseif ($excel_record['file_type'] == 2) {
                if ($excel_record['order_status'] == "1-2-3-4-5") {
                    $filter['order_status'] = '查看全部';
                } else {
                    $order_status = $excel_record['order_status'];
                    $order_status = str_replace('1', '待打款', $order_status);
                    $order_status = str_replace('2', '打款中', $order_status);
                    $order_status = str_replace('3', '已打款', $order_status);
                    $order_status = str_replace('4', '已终止', $order_status);
                    $order_status = str_replace('5', '已作废', $order_status);
                    $filter['order_status'] = $order_status;
                }
            } elseif ($excel_record['file_type'] == 3) {
                if ($excel_record['order_status'] == null) {
                    $filter['order_status'] = '查看全部';
                } else {
                    $tags = Tag::all();
                    $order_status = $excel_record['order_status'];
                    foreach ($tags as $tag) {
                        $order_status = str_replace($tag['id'], $tag['name'], $order_status);
                    }
                    $filter['order_status'] = $order_status;
                }
            }
            if (strtotime($excel_record['start_time']) && strtotime($excel_record['end_time'])) {
                $filter['time_chose'] = $excel_record['time_chose'] == 1 ? '生效时间' : '签约时间';
                $filter['start_time'] = date('Y-m-d', strtotime($excel_record['start_time']));
                $filter['end_time'] = date('Y-m-d', strtotime($excel_record['end_time']));
            }
            $filter['branch_id'] = $excel_record['branch_id'];
            $filter['branch_name'] = $excel_record['branch']['name'];
            if ($excel_record['worker']) {
                // 筛选的员工
                $filter['worker_id'] = $excel_record['worker_id'];
                $filter['worker_name'] = $excel_record['worker']['name'];
            }
            if ($excel_record['user']) {
                // 筛选的客户
                $filter['user_id'] = $excel_record['user_id'];
                $filter['user_name'] = $excel_record['user']['name'];
            }
            if ($excel_record['product']) {
                // 筛选的产品
                $filter['product_id'] = $excel_record['product_id'];
                $filter['product_name'] = $excel_record['product']['name'];
            }
            $record_dic['file_type'] = $excel_record['file_type'];
            $record_dic['is_success'] = $excel_record['is_success'];
            $record_dic['file_url'] = $excel_record['file_url'];
            $record_dic['create_time'] = date('Y-m-d H:i:s', strtotime($excel_record['create_time']));
            $record_dic['filter'] = $filter;
            $record_list[] = $record_dic;
        }
        $start = ($page - 1) * $size;
        $article = array_slice($record_list, $start, $size);
        $counts = count($record_list);
        $datas['record_list'] = $article;
        $datas['total'] = $counts;
        return LMReturn::Success($datas);
    }
}
